package hackthon.service;

import hackthon.core.Constant;
import hackthon.core.MailSender;
import hackthon.core.MyRedis;
import hackthon.dao.EmailDao;
import hackthon.dao.LoginDao;
import hackthon.pojo.Email;
import hackthon.pojo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.jws.soap.SOAPBinding;

/**
 * Created by wuwenhao on 15/1/8.
 */
@Service
public class SendEmailService {

    @Autowired
    public MailSender mailSender;

    @Autowired
    public LoginDao loginDao;

    @Autowired
    public EmailDao emailDao;

    @Autowired
    public MyRedis myRedis;

    public boolean sendEmail(String currentUser, String subject,String content, String toAddress,  String date, int emailId){
        UserInfo userInfo = loginDao.getUserByUsername(currentUser);
        mailSender.host = mailSender.getEmailHost(userInfo.getEmail());
        mailSender.send_from = userInfo.getEmail();
        String addressList[] = toAddress.split(";");
        mailSender.subject=subject;
        try {
            for(int i = 0 ;i <addressList.length;i++){
                String token = Constant.encodeBASE64(emailId+"_"+toAddress);
                content = content + "  "+Constant.REGISTER_URL+token + "  "+date;
                myRedis.setStr(token,token);
                mailSender.sendMail(userInfo.getEmail(),userInfo.getPassword(),addressList[i],content);
            }
        }catch (Exception e){
            return false;
            //e.printStackTrace();
        }

        return true;
    }
    public int storeEmailToDB(String currentUser, String subject, String content,String date, String place,
                              int attendId, int attendMax, int attendMaxAll){
        UserInfo userInfo = loginDao.getUserByUsername(currentUser);
        Email email = new Email();
        email.setAttendId(attendId);
        email.setAttendMax(attendMax);
        email.setAttendMaxAll(attendMaxAll);
        email.setContent(content);
        email.setDate(date);
        email.setPlace(place);
        email.setUserId(userInfo.getUserId());
        email.setSubject(subject);
        return emailDao.addEmail(email);
    }

    public Email getEmailById(int emailId){
        Email email =  emailDao.getEmailById(emailId);
        System.out.println(email);
        return email;
    }
}
